<template>
  <div class="loan-payment-simulator-container">
    <div class="simulator-header">
      <h1>贷款还款模拟器</h1>
      <p>创建模拟贷款还款记录以测试系统功能</p>
    </div>

    <div class="simulator-panel">
      <!-- 还款记录表单 -->
      <div class="payment-form-container">
        <h2>贷款还款详情</h2>
        <form @submit.prevent="addPayment" class="payment-form">
          <div class="form-row">
            <div class="form-group">
              <label for="loan_id">贷款ID <span class="required">*</span></label>
              <select 
                id="loan_id" 
                v-model="paymentForm.loan_id" 
                required
                :class="{ 'error': errors.loan_id }"
                @change="onLoanChange"
              >
                <option value="" disabled>选择贷款</option>
                <option v-for="loan in loans" :key="loan.loan_id" :value="loan.loan_id">
                  {{ loan.loan_id }} - {{ loan.customer_name }} (余额: ¥{{ formatCurrency(loan.remaining_balance) }})
                </option>
              </select>
              <div v-if="errors.loan_id" class="error-message">{{ errors.loan_id }}</div>
            </div>

            <div class="form-group">
              <label for="payment_method">还款方式 <span class="required">*</span></label>
              <select 
                id="payment_method" 
                v-model="paymentForm.payment_method" 
                required
                :class="{ 'error': errors.payment_method }"
              >
                <option value="" disabled>选择还款方式</option>
                <option v-for="method in paymentMethods" :key="method" :value="method">{{ method }}</option>
              </select>
              <div v-if="errors.payment_method" class="error-message">{{ errors.payment_method }}</div>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="amount">还款金额 (¥) <span class="required">*</span></label>
              <div class="input-with-prefix">
                <span class="input-prefix">¥</span>
                <input 
                  type="number" 
                  id="amount" 
                  v-model="paymentForm.amount" 
                  step="0.01" 
                  required
                  :class="{ 'error': errors.amount }"
                  @input="calculateComponents"
                />
              </div>
              <div v-if="errors.amount" class="error-message">{{ errors.amount }}</div>
              <div v-if="selectedLoan" class="field-hint">
                建议月还款额: ¥{{ formatCurrency(selectedLoan.monthly_payment) }}
              </div>
            </div>

            <div class="form-group">
              <label for="payment_date">还款日期 <span class="required">*</span></label>
              <input 
                type="datetime-local" 
                id="payment_date" 
                v-model="paymentForm.payment_date" 
                required
                :class="{ 'error': errors.payment_date }"
              />
              <div v-if="errors.payment_date" class="error-message">{{ errors.payment_date }}</div>
            </div>
          </div>

          <div class="form-row">
            <div class="form-group">
              <label for="due_date">到期日期 <span class="required">*</span></label>
              <input 
                type="datetime-local" 
                id="due_date" 
                v-model="paymentForm.due_date" 
                required
                :class="{ 'error': errors.due_date }"
              />
              <div v-if="errors.due_date" class="error-message">{{ errors.due_date }}</div>
            </div>

            <div class="form-group">
              <label for="status">还款状态</label>
              <select 
                id="status" 
                v-model="paymentForm.status"
                :class="{ 'error': errors.status }"
              >
                <option v-for="status in paymentStatuses" :key="status" :value="status">{{ status }}</option>
              </select>
              <div v-if="errors.status" class="error-message">{{ errors.status }}</div>
            </div>
          </div>

          <!-- 还款组成部分 -->
          <div class="payment-breakdown" v-if="paymentForm.amount && selectedLoan">
            <h3>还款组成</h3>
            <div class="breakdown-grid">
              <div class="breakdown-item">
                <label for="principal_component">本金部分 (¥)</label>
                <div class="input-with-prefix">
                  <span class="input-prefix">¥</span>
                  <input 
                    type="number" 
                    id="principal_component" 
                    v-model="paymentForm.principal_component" 
                    step="0.01" 
                    readonly
                    class="readonly-input"
                  />
                </div>
              </div>

              <div class="breakdown-item">
                <label for="interest_component">利息部分 (¥)</label>
                <div class="input-with-prefix">
                  <span class="input-prefix">¥</span>
                  <input 
                    type="number" 
                    id="interest_component" 
                    v-model="paymentForm.interest_component" 
                    step="0.01" 
                    readonly
                    class="readonly-input"
                  />
                </div>
              </div>

              <div class="breakdown-item">
                <label for="fees">手续费 (¥)</label>
                <div class="input-with-prefix">
                  <span class="input-prefix">¥</span>
                  <input 
                    type="number" 
                    id="fees" 
                    v-model="paymentForm.fees" 
                    step="0.01" 
                    min="0"
                    :class="{ 'error': errors.fees }"
                  />
                </div>
                <div v-if="errors.fees" class="error-message">{{ errors.fees }}</div>
              </div>

              <div class="breakdown-item">
                <label for="reference_number">参考号码</label>
                <input 
                  type="text" 
                  id="reference_number" 
                  v-model="paymentForm.reference_number" 
                  :class="{ 'error': errors.reference_number }"
                  placeholder="自动生成或手动输入"
                />
                <div v-if="errors.reference_number" class="error-message">{{ errors.reference_number }}</div>
              </div>
            </div>
          </div>

          <div class="form-actions">
            <div class="template-actions">
              <button type="button" class="btn-template" @click="generateMonthlyPayment">
                生成月还款
              </button>
              <button type="button" class="btn-template" @click="generateBulkPayments">
                批量生成
              </button>
            </div>
            <button type="button" class="btn-reset" @click="resetForm">重置</button>
            <button type="submit" class="btn-add-payment">添加还款</button>
          </div>
        </form>
      </div>

      <!-- 已添加还款记录列表 -->
      <div class="added-payments">
        <div class="added-payments-header">
          <h2>已添加还款记录 ({{ addedPayments.length }})</h2>
          <div class="added-payments-actions">
            <button 
              class="btn-clear" 
              @click="clearPayments" 
              :disabled="addedPayments.length === 0"
            >
              清空列表
            </button>
            <button 
              class="btn-submit" 
              @click="submitPayments" 
              :disabled="addedPayments.length === 0"
            >
              提交所有还款
            </button>
          </div>
        </div>

        <div class="payments-table-container">
          <table class="payments-table" v-if="addedPayments.length > 0">
            <thead>
              <tr>
                <th>贷款ID</th>
                <th>还款金额</th>
                <th>本金</th>
                <th>利息</th>
                <th>手续费</th>
                <th>还款日期</th>
                <th>到期日期</th>
                <th>还款方式</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(payment, index) in addedPayments" :key="index">
                <td>{{ payment.loan_id }}</td>
                <td class="amount-cell">¥{{ formatCurrency(payment.amount) }}</td>
                <td>¥{{ formatCurrency(payment.principal_component) }}</td>
                <td>¥{{ formatCurrency(payment.interest_component) }}</td>
                <td>¥{{ formatCurrency(payment.fees) }}</td>
                <td>{{ formatDateTime(payment.payment_date) }}</td>
                <td>{{ formatDateTime(payment.due_date) }}</td>
                <td>{{ payment.payment_method }}</td>
                <td>
                  <span 
                    class="status-badge" 
                    :class="getStatusClass(payment.status)"
                  >
                    {{ payment.status }}
                  </span>
                </td>
                <td>
                  <button class="btn-delete" @click="removePayment(index)">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
          <div class="no-payments" v-else>
            <p>暂无添加的还款记录</p>
            <p class="hint">使用上方表单添加还款记录</p>
          </div>
        </div>

        <!-- 统计信息 -->
        <div class="payment-summary" v-if="addedPayments.length > 0">
          <div class="summary-item">
            <span class="summary-label">总还款金额:</span>
            <span class="summary-value">¥{{ formatCurrency(totalPaymentAmount) }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">总本金:</span>
            <span class="summary-value">¥{{ formatCurrency(totalPrincipal) }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">总利息:</span>
            <span class="summary-value">¥{{ formatCurrency(totalInterest) }}</span>
          </div>
          <div class="summary-item">
            <span class="summary-label">总手续费:</span>
            <span class="summary-value">¥{{ formatCurrency(totalFees) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 批量生成模态框 -->
    <div class="modal" v-if="showBulkModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>批量生成还款记录</h2>
          <button class="modal-close" @click="showBulkModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="bulk_months">生成月数</label>
            <input 
              type="number" 
              id="bulk_months" 
              v-model="bulkForm.months" 
              min="1" 
              max="12"
              placeholder="输入要生成的月数"
            />
          </div>
          <div class="form-group">
            <label for="bulk_start_date">开始日期</label>
            <input 
              type="date" 
              id="bulk_start_date" 
              v-model="bulkForm.startDate"
            />
          </div>
          <div class="form-actions">
            <button type="button" class="btn-cancel" @click="showBulkModal = false">取消</button>
            <button type="button" class="btn-confirm" @click="confirmBulkGeneration">生成</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 提交确认模态框 -->
    <div class="modal" v-if="showSubmitModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>确认提交</h2>
          <button class="modal-close" @click="showSubmitModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <p>您确定要提交 <strong>{{ addedPayments.length }}</strong> 条还款记录吗？</p>
          <p>提交后，这些记录将被保存到数据库中。</p>
          
          <div class="submit-summary">
            <div class="summary-item">
              <span class="summary-label">总还款记录:</span>
              <span class="summary-value">{{ addedPayments.length }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">总还款金额:</span>
              <span class="summary-value">¥{{ formatCurrency(totalPaymentAmount) }}</span>
            </div>
            <div class="summary-item">
              <span class="summary-label">涉及贷款:</span>
              <span class="summary-value">{{ uniqueLoanIds }}</span>
            </div>
          </div>
          
          <div class="form-actions">
            <button type="button" class="btn-cancel" @click="showSubmitModal = false">取消</button>
            <button type="button" class="btn-confirm" @click="confirmSubmit">确认提交</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 成功提示模态框 -->
    <div class="modal" v-if="showSuccessModal">
      <div class="modal-content success-modal">
        <div class="modal-header">
          <h2>提交成功</h2>
          <button class="modal-close" @click="showSuccessModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <div class="success-icon">✓</div>
          <p>已成功提交 <strong>{{ submittedCount }}</strong> 条还款记录！</p>
          
          <div class="form-actions">
            <button type="button" class="btn-confirm" @click="closeSuccessModal">确定</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 模态框遮罩 -->
    <div class="modal-overlay" v-if="showBulkModal || showSubmitModal || showSuccessModal" @click="closeAllModals"></div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';

// Get route params
const route = useRoute();
const loanIdFromRoute = computed(() => route.params.id ? parseInt(route.params.id) : null);

// 模拟贷款数据
const loans = ref([
  { 
    loan_id: 1001, 
    customer_name: '张三', 
    loan_amount: 500000, 
    remaining_balance: 450000, 
    interest_rate: 5.2, 
    monthly_payment: 2847.15,
    loan_term: 240
  },
  { 
    loan_id: 1002, 
    customer_name: '李四', 
    loan_amount: 300000, 
    remaining_balance: 280000, 
    interest_rate: 6.8, 
    monthly_payment: 2156.89,
    loan_term: 180
  },
  { 
    loan_id: 1003, 
    customer_name: '王五', 
    loan_amount: 800000, 
    remaining_balance: 720000, 
    interest_rate: 4.8, 
    monthly_payment: 4187.32,
    loan_term: 360
  },
  { 
    loan_id: 1004, 
    customer_name: '赵六', 
    loan_amount: 150000, 
    remaining_balance: 135000, 
    interest_rate: 7.5, 
    monthly_payment: 1398.43,
    loan_term: 120
  }
]);

// 还款方式
const paymentMethods = [
  '银行转账',
  '自动扣款',
  '现金支付',
  '支票支付',
  '网上银行',
  '手机银行',
  '第三方支付',
  '柜台支付'
];

// 还款状态
const paymentStatuses = [
  'Completed',
  'Pending',
  'Failed',
  'Cancelled',
  'Processing'
];

// 表单数据
const paymentForm = reactive({
  loan_id: '',
  amount: '',
  principal_component: '',
  interest_component: '',
  fees: 0,
  payment_date: formatDateForInput(new Date()),
  due_date: formatDateForInput(new Date()),
  payment_method: '',
  status: 'Completed',
  reference_number: ''
});

// 批量生成表单
const bulkForm = reactive({
  months: 6,
  startDate: formatDateForInput(new Date()).split('T')[0]
});

// 错误信息
const errors = reactive({});

// 已添加的还款记录
const addedPayments = ref([]);

// 模态框状态
const showBulkModal = ref(false);
const showSubmitModal = ref(false);
const showSuccessModal = ref(false);
const submittedCount = ref(0);

// 计算属性
const selectedLoan = computed(() => {
  return loans.value.find(loan => loan.loan_id === parseInt(paymentForm.loan_id));
});

const totalPaymentAmount = computed(() => {
  return addedPayments.value.reduce((sum, payment) => sum + parseFloat(payment.amount), 0);
});

const totalPrincipal = computed(() => {
  return addedPayments.value.reduce((sum, payment) => sum + parseFloat(payment.principal_component), 0);
});

const totalInterest = computed(() => {
  return addedPayments.value.reduce((sum, payment) => sum + parseFloat(payment.interest_component), 0);
});

const totalFees = computed(() => {
  return addedPayments.value.reduce((sum, payment) => sum + parseFloat(payment.fees), 0);
});

const uniqueLoanIds = computed(() => {
  const loanIds = [...new Set(addedPayments.value.map(p => p.loan_id))];
  return loanIds.length > 3 ? `${loanIds.slice(0, 3).join(', ')} 等${loanIds.length}个` : loanIds.join(', ');
});

// 方法
function onLoanChange() {
  if (selectedLoan.value) {
    paymentForm.amount = selectedLoan.value.monthly_payment;
    calculateComponents();
    generateReferenceNumber();
  }
}

function calculateComponents() {
  if (!paymentForm.amount || !selectedLoan.value) {
    return;
  }
  
  const amount = parseFloat(paymentForm.amount);
  const remainingBalance = selectedLoan.value.remaining_balance;
  const monthlyRate = selectedLoan.value.interest_rate / 100 / 12;
  
  // 计算利息部分（基于剩余本金）
  const interestComponent = remainingBalance * monthlyRate;
  
  // 计算本金部分
  const principalComponent = Math.max(0, amount - interestComponent - parseFloat(paymentForm.fees || 0));
  
  paymentForm.interest_component = interestComponent.toFixed(2);
  paymentForm.principal_component = principalComponent.toFixed(2);
}

function generateReferenceNumber() {
  const timestamp = Date.now();
  const loanId = paymentForm.loan_id || '0000';
  paymentForm.reference_number = `PAY${loanId}${timestamp}`;
}

function generateMonthlyPayment() {
  if (!selectedLoan.value) {
    alert('请先选择贷款');
    return;
  }
  
  paymentForm.amount = selectedLoan.value.monthly_payment;
  calculateComponents();
  
  // 设置到期日期为下个月同一天
  const dueDate = new Date();
  dueDate.setMonth(dueDate.getMonth() + 1);
  paymentForm.due_date = formatDateForInput(dueDate);
  
  generateReferenceNumber();
}

function generateBulkPayments() {
  if (!selectedLoan.value) {
    alert('请先选择贷款');
    return;
  }
  
  showBulkModal.value = true;
}

function confirmBulkGeneration() {
  if (!selectedLoan.value || !bulkForm.months) {
    return;
  }
  
  const startDate = new Date(bulkForm.startDate);
  const loan = selectedLoan.value;
  
  for (let i = 0; i < bulkForm.months; i++) {
    const paymentDate = new Date(startDate);
    paymentDate.setMonth(paymentDate.getMonth() + i);
    
    const dueDate = new Date(paymentDate);
    dueDate.setDate(dueDate.getDate() + 5); // 到期日期比还款日期晚5天
    
    const remainingBalance = loan.remaining_balance - (i * loan.monthly_payment * 0.7); // 简化计算
    const monthlyRate = loan.interest_rate / 100 / 12;
    const interestComponent = remainingBalance * monthlyRate;
    const principalComponent = loan.monthly_payment - interestComponent;
    
    const payment = {
      loan_id: loan.loan_id,
      amount: loan.monthly_payment,
      principal_component: Math.max(0, principalComponent),
      interest_component: Math.max(0, interestComponent),
      fees: 0,
      payment_date: formatDateForInput(paymentDate),
      due_date: formatDateForInput(dueDate),
      payment_method: '自动扣款',
      status: 'Completed',
      reference_number: `PAY${loan.loan_id}${paymentDate.getTime()}`
    };
    
    addedPayments.value.push(payment);
  }
  
  showBulkModal.value = false;
}

function addPayment() {
  if (!validateForm()) {
    return;
  }
  
  const newPayment = {
    loan_id: parseInt(paymentForm.loan_id),
    amount: parseFloat(paymentForm.amount),
    principal_component: parseFloat(paymentForm.principal_component),
    interest_component: parseFloat(paymentForm.interest_component),
    fees: parseFloat(paymentForm.fees || 0),
    payment_date: paymentForm.payment_date,
    due_date: paymentForm.due_date,
    payment_method: paymentForm.payment_method,
    status: paymentForm.status,
    reference_number: paymentForm.reference_number || generateReferenceNumber()
  };
  
  addedPayments.value.push(newPayment);
  resetForm();
}

function resetForm() {
  Object.keys(paymentForm).forEach(key => {
    if (key === 'payment_date' || key === 'due_date') {
      paymentForm[key] = formatDateForInput(new Date());
    } else if (key === 'status') {
      paymentForm[key] = 'Completed';
    } else if (key === 'fees') {
      paymentForm[key] = 0;
    } else {
      paymentForm[key] = '';
    }
  });
  errors.value = {};
}

function validateForm() {
  errors.value = {};
  let isValid = true;
  
  if (!paymentForm.loan_id) {
    errors.loan_id = '请选择贷款';
    isValid = false;
  }
  
  if (!paymentForm.amount) {
    errors.amount = '请输入还款金额';
    isValid = false;
  } else if (isNaN(paymentForm.amount) || parseFloat(paymentForm.amount) <= 0) {
    errors.amount = '还款金额必须大于0';
    isValid = false;
  }
  
  if (!paymentForm.payment_method) {
    errors.payment_method = '请选择还款方式';
    isValid = false;
  }
  
  if (!paymentForm.payment_date) {
    errors.payment_date = '请选择还款日期';
    isValid = false;
  }
  
  if (!paymentForm.due_date) {
    errors.due_date = '请选择到期日期';
    isValid = false;
  }
  
  if (paymentForm.fees && (isNaN(paymentForm.fees) || parseFloat(paymentForm.fees) < 0)) {
    errors.fees = '手续费不能为负数';
    isValid = false;
  }
  
  if (paymentForm.reference_number && paymentForm.reference_number.length > 100) {
    errors.reference_number = '参考号码不能超过100个字符';
    isValid = false;
  }
  
  return isValid;
}

function removePayment(index) {
  addedPayments.value.splice(index, 1);
}

function clearPayments() {
  if (confirm('确定要清空所有已添加的还款记录吗？')) {
    addedPayments.value = [];
  }
}

function submitPayments() {
  if (addedPayments.value.length === 0) {
    return;
  }
  
  showSubmitModal.value = true;
}

function confirmSubmit() {
  console.log('提交还款记录:', addedPayments.value);
  
  submittedCount.value = addedPayments.value.length;
  showSubmitModal.value = false;
  showSuccessModal.value = true;
  
  addedPayments.value = [];
}

function closeSuccessModal() {
  showSuccessModal.value = false;
}

function closeAllModals() {
  showBulkModal.value = false;
  showSubmitModal.value = false;
  showSuccessModal.value = false;
}

// 辅助函数
function formatDateForInput(date) {
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day}T${hours}:${minutes}`;
}

function formatDateTime(dateString) {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  }).format(date);
}

function formatCurrency(value) {
  return new Intl.NumberFormat('zh-CN', {
    style: 'decimal',
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(value);
}

function getStatusClass(status) {
  switch (status) {
    case 'Completed': return 'status-completed';
    case 'Pending': return 'status-pending';
    case 'Failed': return 'status-failed';
    case 'Cancelled': return 'status-cancelled';
    case 'Processing': return 'status-processing';
    default: return '';
  }
}

// 初始化
onMounted(() => {
  console.log('贷款还款模拟器已加载');
  
  // If loan ID is provided in the route, pre-select it
  if (loanIdFromRoute.value) {
    const matchingLoan = loans.value.find(loan => loan.loan_id === loanIdFromRoute.value);
    if (matchingLoan) {
      paymentForm.loan_id = matchingLoan.loan_id;
      onLoanChange();
    }
  }
});
</script>

<style scoped>
.loan-payment-simulator-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 2rem 1rem;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  color: #333;
}

.simulator-header {
  text-align: center;
  margin-bottom: 2rem;
}

.simulator-header h1 {
  font-size: 2rem;
  font-weight: 600;
  color: #1e40af;
  margin-bottom: 0.5rem;
}

.simulator-header p {
  font-size: 1.125rem;
  color: #555;
}

/* Simulator Panel */
.simulator-panel {
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  padding: 1.5rem;
  margin-bottom: 2rem;
}

.simulator-panel h2 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1e40af;
  margin-bottom: 1rem;
}

/* Payment Form */
.payment-form-container {
  margin-bottom: 2rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.payment-form {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.form-group {
  flex: 1;
  min-width: 200px;
}

.form-group label {
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  margin-bottom: 0.5rem;
  color: #555;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid #d1d5db;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  transition: border-color 0.2s;
}

.input-with-prefix {
  position: relative;
}

.input-prefix {
  position: absolute;
  left: 0.75rem;
  top: 0.75rem;
  color: #555;
}

.input-with-prefix input {
  padding-left: 1.5rem;
}

.form-group input:focus,
.form-group select:focus {
  border-color: #1e40af;
  outline: none;
  box-shadow: 0 0 0 2px rgba(30, 64, 175, 0.1);
}

.form-group input.error,
.form-group select.error {
  border-color: #ef4444;
}

.readonly-input {
  background-color: #f9fafb;
  color: #6b7280;
}

.error-message {
  color: #ef4444;
  font-size: 0.75rem;
  margin-top: 0.25rem;
}

.field-hint {
  color: #6b7280;
  font-size: 0.75rem;
  margin-top: 0.25rem;
}

.required {
  color: #ef4444;
}

/* Payment Breakdown */
.payment-breakdown {
  background-color: #f8fafc;
  border-radius: 0.5rem;
  padding: 1.5rem;
  border-left: 4px solid #1e40af;
}

.payment-breakdown h3 {
  font-size: 1rem;
  font-weight: 600;
  color: #1e40af;
  margin-bottom: 1rem;
}

.breakdown-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.breakdown-item {
  display: flex;
  flex-direction: column;
}

.breakdown-item label {
  font-size: 0.875rem;
  font-weight: 500;
  margin-bottom: 0.5rem;
  color: #555;
}

/* Form Actions */
.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
  margin-top: 1rem;
}

.template-actions {
  display: flex;
  gap: 0.5rem;
}

.btn-template,
.btn-reset,
.btn-add-payment,
.btn-clear,
.btn-submit,
.btn-cancel,
.btn-confirm {
  padding: 0.75rem 1.5rem;
  border-radius: 0.375rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.btn-template {
  background-color: #f3f4f6;
  color: #374151;
  border: 1px solid #d1d5db;
}

.btn-template:hover {
  background-color: #e5e7eb;
}

.btn-reset {
  background-color: white;
  color: #555;
  border: 1px solid #d1d5db;
}

.btn-reset:hover {
  background-color: #f9fafb;
}

.btn-add-payment,
.btn-submit,
.btn-confirm {
  background-color: #1e40af;
  color: white;
  border: none;
}

.btn-add-payment:hover,
.btn-submit:hover,
.btn-confirm:hover {
  background-color: #1e3a8a;
}

.btn-clear,
.btn-cancel {
  background-color: white;
  color: #555;
  border: 1px solid #d1d5db;
}

.btn-clear:hover,
.btn-cancel:hover {
  background-color: #f9fafb;
}

.btn-clear:disabled,
.btn-submit:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* Added Payments */
.added-payments {
  margin-bottom: 2rem;
}

.added-payments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.added-payments-actions {
  display: flex;
  gap: 0.75rem;
}

.payments-table-container {
  overflow-x: auto;
}

.payments-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 1.5rem;
}

.payments-table th,
.payments-table td {
  padding: 0.75rem 1rem;
  text-align: left;
  border-bottom: 1px solid #e5e7eb;
}

.payments-table th {
  background-color: #f9fafb;
  font-weight: 600;
  color: #4b5563;
}

.payments-table tr:hover {
  background-color: #f9fafb;
}

.amount-cell {
  font-weight: 500;
  color: #059669;
}

.status-badge {
  display: inline-block;
  padding: 0.25rem 0.5rem;
  border-radius: 9999px;
  font-size: 0.75rem;
  font-weight: 500;
}

.status-completed {
  background-color: #dcfce7;
  color: #166534;
}

.status-pending {
  background-color: #fef3c7;
  color: #92400e;
}

.status-failed {
  background-color: #fee2e2;
  color: #991b1b;
}

.status-cancelled {
  background-color: #f3f4f6;
  color: #4b5563;
}

.status-processing {
  background-color: #dbeafe;
  color: #1e40af;
}

.btn-delete {
  padding: 0.25rem 0.5rem;
  background-color: #ef4444;
  color: white;
  border: none;
  border-radius: 0.25rem;
  font-size: 0.75rem;
  cursor: pointer;
}

.btn-delete:hover {
  background-color: #dc2626;
}

.no-payments {
  text-align: center;
  padding: 2rem 0;
  color: #6b7280;
}

.hint {
  font-size: 0.875rem;
  color: #9ca3af;
  margin-top: 0.5rem;
}

/* Payment Summary */
.payment-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  padding: 1rem;
  background-color: #f8fafc;
  border-radius: 0.5rem;
  border-left: 4px solid #059669;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.summary-label {
  font-weight: 500;
  color: #4b5563;
}

.summary-value {
  font-weight: 600;
  color: #059669;
}

/* Modal Styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
}

.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 101;
  width: 90%;
  max-width: 500px;
}

.modal-content {
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.success-modal {
  max-width: 400px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.modal-header h2 {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1e40af;
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #6b7280;
}

.modal-body {
  padding: 1.5rem;
}

.submit-summary {
  margin: 1.5rem 0;
  padding: 1rem;
  background-color: #f9fafb;
  border-radius: 0.375rem;
}

.success-icon {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 4rem;
  height: 4rem;
  margin: 0 auto 1.5rem;
  background-color: #dcfce7;
  color: #166534;
  font-size: 2rem;
  border-radius: 50%;
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .form-row {
    flex-direction: column;
  }
  
  .form-group {
    min-width: 100%;
  }
  
  .form-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .template-actions {
    justify-content: center;
  }
  
  .added-payments-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }
  
  .added-payments-actions {
    width: 100%;
  }
  
  .btn-clear,
  .btn-submit {
    flex: 1;
  }
  
  .breakdown-grid {
    grid-template-columns: 1fr;
  }
  
  .payment-summary {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .btn-template,
  .btn-reset,
  .btn-add-payment,
  .btn-clear,
  .btn-submit,
  .btn-cancel,
  .btn-confirm {
    width: 100%;
  }
  
  .template-actions {
    flex-direction: column;
  }
}
</style>
